local modname = minetest.get_current_modname()
local build_helper_node = modname .. ":node"

local KEY = "aux1"
local TIMEOUT = 0.25
local DEFAULT_RANGE = 4

minetest.register_node(build_helper_node, {
	description = "Build helper",
	groups = {not_in_creative_inventory = 1},
	drawtype = "airlike",
	paramtype = "light",
	pointable = true,
	walkable = false,
	on_construct = function(pos)
		local timer = minetest.get_node_timer(pos)
		timer:start(TIMEOUT)
	end,
	on_timer = function(pos)
		minetest.set_node(pos, {name = "air"})
	end,
})

local function get_range(player)
	local wield = player:get_wielded_item()
	local def = wield:get_definition()
	if def then
		return def.range or DEFAULT_RANGE
	else
		return DEFAULT_RANGE
	end
end

local function get_pointed_thing(player)
	local pos = player:get_pos()
	local eye_height = player:get_properties().eye_height
	pos.y = pos.y + eye_height

	local lookdir = vector.multiply(player:get_look_dir(), get_range(player))
	local raycast = Raycast(pos, vector.add(pos, lookdir))
	local next = raycast:next()
	if next and next.ref == player then
		next = raycast:next()
	end
	return next
end

local function place_build_help(player)
	local pointed_thing = get_pointed_thing(player)
	if not pointed_thing or pointed_thing.type ~= "node" then
		return
	end
	local above = pointed_thing.above
	local under = pointed_thing.under
	local abovenode = minetest.get_node(above)
	local undernode = minetest.get_node(under)
	if (abovenode.name == "air") and undernode.name ~= build_helper_node then
		minetest.place_node(above, {name = build_helper_node})
	elseif undernode.name == build_helper_node then
		local timer = minetest.get_node_timer(under)
		timer:start(TIMEOUT)
	end
end

local timer = 0
minetest.register_globalstep(function(dtime)
	timer = timer + dtime
	if true or timer > 0.25 then
		timer = 0
		for i, player in ipairs(minetest.get_connected_players()) do
			local ctrl = player:get_player_control()
			if ctrl[KEY] then
				place_build_help(player)
			end
		end
	end
end)

minetest.register_lbm({
	label = "Build helper disappearing",
	name = modname .. ":remove_build_helpers",
	nodenames = {build_helper_node},
	run_at_every_load = true,
	action = function(pos, node)
		minetest.set_node(pos, {name = "air"})
	end
	
})
